package com.goldenlight.fvms.manager.controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.goldenlight.fvms.manager.entity.ProductFreeApply;
import com.goldenlight.fvms.manager.excelentity.ProductCountExcelEntity;
import com.goldenlight.fvms.manager.service.ProductFreeApplyService;
import com.goldenlight.fvms.manager.utils.ExcelUtils;
import com.goldenlight.fvms.manager.utils.GlobalCont;
import com.goldenlight.fvms.manager.vo.Request;
import com.goldenlight.fvms.manager.vo.Response;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 生产生活车辆申请信息表 前端控制器
 * </p>
 *
 * @author luocx
 * @since 2018-12-08
 */
@Api("生产生活车辆申请信息 API")
@RestController
@RequestMapping("/productFreeApply")
public class ProductFreeApplyController {

    private Logger logger = LoggerFactory.getLogger(ProductFreeApplyController.class);
    @Autowired
    private ProductFreeApplyService productFreeApplyService;

    @ApiOperation(value = "根据productFreeApply查询信息", notes = "查询列表")
    @PostMapping("/getListByPage")
    public Response getListByPage(@RequestBody Request<ProductFreeApply> request) {
        ProductFreeApply productFreeApply = request.getData();
        Page page = request.getPage();
        logger.info("productFreeApply:{}", productFreeApply);
        QueryWrapper<ProductFreeApply> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(productFreeApply.getCarNum())) {
            wrapper.lambda().like(ProductFreeApply::getCarNum, productFreeApply.getCarNum());
        }
        if (!StringUtils.isEmpty(productFreeApply.getCarApplyUnit())) {
            wrapper.lambda().like(ProductFreeApply::getCarApplyUnit, productFreeApply.getCarApplyUnit());
        }
        if (!StringUtils.isEmpty(productFreeApply.getCarBussType())) {
            wrapper.lambda().like(ProductFreeApply::getCarBussType, productFreeApply.getCarBussType());
        }
        if (null != productFreeApply.getCarType() && productFreeApply.getCarType() != 0) {
            wrapper.lambda().eq(ProductFreeApply::getCarType, productFreeApply.getCarType());
        }
        if (null != productFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(ProductFreeApply::getBuildVersion, productFreeApply.getBuildVersion());
        }
        if (null != productFreeApply.getTimeStamp()) {
            wrapper.lambda().and(e -> e.gt(ProductFreeApply::getTimeStamp, productFreeApply.getTimeStamp()));
            Calendar c = Calendar.getInstance();
            c.setTime(productFreeApply.getTimeStamp());
            c.add(Calendar.DAY_OF_MONTH, 1);
            wrapper.lambda().and(e -> e.lt(ProductFreeApply::getTimeStamp, c.getTime()));
        }
        wrapper.orderByDesc("build_version");
        IPage productFreeApplies = productFreeApplyService.page(page, wrapper);
        return Response.build(200, GlobalCont.SUCCESS, productFreeApplies);
    }


    @ApiOperation(value = "根据productFreeApply查询信息", notes = "查询列表")
    @PostMapping("/getList")
    public Response getList(@ModelAttribute ProductFreeApply productFreeApply) {
        QueryWrapper<ProductFreeApply> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(productFreeApply.getCarNum())) {
            wrapper.lambda().like(ProductFreeApply::getCarNum, productFreeApply.getCarNum());
        }
        if (!StringUtils.isEmpty(productFreeApply.getCarApplyUnit())) {
            wrapper.lambda().like(ProductFreeApply::getCarApplyUnit, productFreeApply.getCarApplyUnit());
        }
        if (!StringUtils.isEmpty(productFreeApply.getCarBussType())) {
            wrapper.lambda().like(ProductFreeApply::getCarBussType, productFreeApply.getCarBussType());
        }
        if (null != productFreeApply.getCarType() && productFreeApply.getCarType() != 0) {
            wrapper.lambda().eq(ProductFreeApply::getCarType, productFreeApply.getCarType());
        }
        if (null != productFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(ProductFreeApply::getBuildVersion, productFreeApply.getBuildVersion());
        }
        if (null != productFreeApply.getTimeStamp()) {
            wrapper.lambda().and(e -> e.gt(ProductFreeApply::getTimeStamp, productFreeApply.getTimeStamp()));
            Calendar c = Calendar.getInstance();
            c.setTime(productFreeApply.getTimeStamp());
            c.add(Calendar.DAY_OF_MONTH, 1);
            wrapper.lambda().and(e -> e.lt(ProductFreeApply::getTimeStamp, c.getTime()));
        }
        wrapper.orderByDesc("build_version");
        List<ProductFreeApply> productFreeApplies = productFreeApplyService.list(wrapper);
        return Response.build(200, GlobalCont.SUCCESS, productFreeApplies);
    }

    @ApiOperation(value = "根据productFreeApply导出excel", notes = "导出excel")
    @PostMapping("/exportExcel")
    public void exportExcel(@ModelAttribute ProductFreeApply productFreeApply, HttpServletResponse response) {
        logger.info("exportExcel:{}", productFreeApply);
        List<ProductFreeApply> list = (List<ProductFreeApply>) this.getList(productFreeApply).getData();
        String titleName = "车辆免费通行批准明细单";
        if (null != productFreeApply.getCarType()) {
            if (productFreeApply.getCarType() == 1) {
                titleName = "集团公司养护生产车辆免费通行批准明细单（路网）";
            } else if (productFreeApply.getCarType() == 2) {
                titleName = "集团公司养护生产、生活管理车辆免费通行批准明细单（路网）";
            } else if (productFreeApply.getCarType() == 3) {
                titleName = "集团公司养护生产车辆免费通行批准明细单（区间）";
            } else if (productFreeApply.getCarType() == 4) {
                titleName = "集团公司养护生产、生活管理车辆免费通行批准明细单（区间）";
            }
        }
        ExcelUtils.exportExcel(list, titleName, "sheet1",
                ProductFreeApply.class, "导出信息.xlsx", true, response);
    }

    @ApiOperation(value = "根据productFreeApply更新信息", notes = "更新数据库")
    @PostMapping("/updateEmployFreeApply")
    public Response updateRecord(@ModelAttribute ProductFreeApply productFreeApply) {
        logger.info("employFreeApply:{}", productFreeApply);
        Wrapper<ProductFreeApply> wrapper = new UpdateWrapper<>();
        ((UpdateWrapper<ProductFreeApply>) wrapper).eq("CAR_NUM", productFreeApply.getCarNum());
        boolean result = productFreeApplyService.update(productFreeApply, wrapper);
        if (result) {
            return Response.build(000, "更新成功", null);
        } else {
            return Response.build(200, "更新失败", null);
        }
    }


    @ApiOperation(value = "根据productFreeApply更新信息", notes = "更新数据库")
    @PostMapping("/Statistics")
    public Response statistics(@RequestBody Request<ProductFreeApply> request) {
        logger.info("request:{}", request);
        logger.info("page:{}", request.getPage().getCurrent());

        ProductFreeApply productFreeApply = request.getData();
        Page page = request.getPage();
        QueryWrapper<ProductFreeApply> wrapper = getCountQueryWrapper(productFreeApply);

        IPage result = productFreeApplyService.page(page, wrapper);
        return Response.build(200, GlobalCont.SUCCESS, result);
    }

    private QueryWrapper<ProductFreeApply> getCountQueryWrapper(ProductFreeApply productFreeApply) {
        QueryWrapper<ProductFreeApply> wrapper = new QueryWrapper<>();
        wrapper.select("CAR_APPLY_UNIT", "CAR_TYPE", "BUILD_VERSION", "count(1) count", "car_buss_type");
        if (!StringUtils.isEmpty(productFreeApply.getCarApplyUnit())) {
            wrapper.lambda().like(ProductFreeApply::getCarApplyUnit, productFreeApply.getCarApplyUnit());
        }
        if (null != productFreeApply.getCarType() && productFreeApply.getCarType() != 0) {
            wrapper.lambda().eq(ProductFreeApply::getCarType, productFreeApply.getCarType());
        }
        if (null != productFreeApply.getBuildVersion()) {
            wrapper.lambda().eq(ProductFreeApply::getBuildVersion, productFreeApply.getBuildVersion());
        }
        wrapper.lambda().groupBy(ProductFreeApply::getCarBussType, ProductFreeApply::getCarType, ProductFreeApply::getBuildVersion).orderByDesc(ProductFreeApply::getBuildVersion);
        return wrapper;
    }

    @ApiOperation(value = "根据productFreeApply导出excel", notes = "导出excel")
    @PostMapping("/exportExcelCount")
    public void exportExcelCount(@RequestBody Request<ProductFreeApply> request, HttpServletResponse response) {
        ProductFreeApply productFreeApply = request.getData();
        QueryWrapper<ProductFreeApply> wrapper = getCountQueryWrapper(productFreeApply);
        List<ProductFreeApply> list = productFreeApplyService.list(wrapper);

        List<ProductCountExcelEntity> productCountExcelEntities = list.parallelStream().map(item -> ProductCountExcelEntity
                .builder().carApplyUnit(item.getCarApplyUnit()).carBussType(item.getCarBussType())
                .carType(item.getCarType()).buildVersion(item.getBuildVersion()).count(item.getCount()).build())
                .collect(Collectors.toList());

        String titleName = "车辆免费通行批准汇总信息";
        if (null != productFreeApply.getCarType()) {
            if (productFreeApply.getCarType() == 1) {
                titleName = "集团公司养护生产车辆免费通行批准汇总信息（路网）";
            } else if (productFreeApply.getCarType() == 2) {
                titleName = "集团公司养护生产、生活管理车辆免费通行批准汇总信息（路网）";
            } else if (productFreeApply.getCarType() == 3) {
                titleName = "集团公司养护生产车辆免费通行批准汇总信息（区间）";
            } else if (productFreeApply.getCarType() == 4) {
                titleName = "集团公司养护生产、生活管理车辆免费通行批准汇总信息（区间）";
            }
        }
        ExcelUtils.exportExcel(productCountExcelEntities, titleName, "sheet1",
                ProductCountExcelEntity.class, "导出信息.xlsx", true, response);
    }


}

